

console.log("yuenan stock ajax")


setInterval(()=>{
    if(!header_quickView){
        clickButton();
    }

},2000)



function simulateClick(element) {
    if (element) {
        // 创建 MouseEvent 对象，表示鼠标点击事件
        const mouseEvent = new MouseEvent('mousedown', {
            bubbles: true, // 是否冒泡
            cancelable: true, // 是否可取消
            view: window
        });

        // 先触发 mousedown 事件
        element.dispatchEvent(mouseEvent);

        // 创建和触发 mouseup 事件
        const mouseUpEvent = new MouseEvent('mouseup', {
            bubbles: true,
            cancelable: true,
            view: window
        });

        element.dispatchEvent(mouseUpEvent);

        // 创建和触发 click 事件
        const clickEvent = new MouseEvent('click', {
            bubbles: true,
            cancelable: true,
            view: window
        });

        element.dispatchEvent(clickEvent);
    } else {
        console.log('元素未找到');
    }
}

function clickButton(){

    const closeBox = document.querySelector('.captcha_canvas_close_box');
    if (closeBox) {
        return
    }

    var button = document.querySelector('.product-card__add-btn.price-wrapper__addbag-btn');
    simulateClick(button);

}

var api1_fail_number = 0;
var api2_fail_number = 0;
var api3_fail_number = 0;
var api4_fail_number = 0;
var success_time = 0;

var header_quickView = "";
var header_header_static_v2 = "";
var header_header_realtime = "";
var useLocalHeader_realtime = false;
var useLocalHeader_quickview = false;
var last_fail_api_index = 0 ;
var run_index = 0;
var sm_eror = false;
chrome.runtime.onMessage.addListener(async (msg, sender) => {

    console.log(msg);
    console.log(sm_eror)
    if(msg.type==='header_quickView'){
        header_quickView = msg.headers;
        useLocalHeader_quickview = false;
        sm_eror = false;
    }else if(msg.type==='header_static_v2'){
        header_header_static_v2 = msg.headers;
        useLocalHeader = false;
    }else if(msg.type==='header_realtime'){
        header_header_realtime = msg.headers;
        useLocalHeader_realtime = false;
    }else if(header_quickView && (api3_fail_number<=4 || api4_fail_number<=2 ||api2_fail_number <=4)){

        if(api3_fail_number <= 4){
            getDataByApiStaticV2(msg);
        }else if(api4_fail_number <=2){
            getDataByQuickView(msg);
        }else if(api2_fail_number <=4){
            get_goods_detail_realtime_data(msg);
        }else{
            block();
        }

    }else if(api1_fail_number <=2){
        getDataByApiByProductRealTime(msg);
    }else if(sm_eror===true){
        block();
    }
})

function block(){
    console.log("sheinblock_yuenanstock");
    fail_number = 0;
    var type = "sheinblock_yuenanstock";
    let block_time = 600;//秒
    chrome.runtime.sendMessage({ data: {type ,block_time}, close: false });
    let this_lock_time = (block_time -5) * 1000;
    setTimeout(() => {
        location.reload()
    },this_lock_time);
}

function getDataByQuickView(msg){
    console.log("start api 4")
    const url = 'https://s1.shein.com/api/productInfo/quickView/get?_ver=1.1.8&_lang=en&goods_id='+msg.data.goods_id+'&mallCode=1&lockmall=0&isQuick=1&bid=my'; // 替换为您的接口地址

    let requestHeader= getHeaderByType("quickview");

    console.log(requestHeader);
    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            console.log(data);
            if(data['code']==='836100'){
                api4_fail_number++;
                sm_eror= true;
                //clickButton();
                last_fail_api_index = 4;
                console.log("api4_fail_number:"+api4_fail_number);
            }else{
                api4_fail_number = 0;
                getStockByQuickView(data,msg.data.id,msg);
            }

        })
        .catch(error => {
            api4_fail_number ++;
            last_fail_api_index = 4;
            console.log("api4_fail_number:"+api4_fail_number);
            console.log(error)
        });

}
function getDataByApiByProductRealTime(msg){
    console.log("start api 1");
    var goods_id = msg.data.goods_id;
    const url = 'https://s1.shein.com/api/productInfo/realTimeData/query?_ver=1.1.8&_lang=en'; // 替换为您的接口地址
    const payload = {
        goods_id: msg.data.goods_id,
        mallCode: "1",
        tsp: {},
        specialSceneType: 0,
        tags: [
            { tagId: "2422", tagValueId: ["9680"] },
            { tagId: "2423", tagValueId: ["83281"] },
            { tagId: "3199", tagValueId: ["502"] },
            { tagId: "3864", tagValueId: ["12.72"] },
            { tagId: "3865", tagValueId: ["12.64"] },
            { tagId: "3866", tagValueId: ["12.64"] },
            { tagId: "4015", tagValueId: ["12.74"] },
            { tagId: "4016", tagValueId: ["12.74"] },
            { tagId: "4017", tagValueId: ["12.74"] },
            { tagId: "4018", tagValueId: ["2"] },
            { tagId: "4448", tagValueId: ["67"] },
            { tagId: "4607", tagValueId: ["2388"] },
            { tagId: "60007749", tagValueId: ["1"] },
            { tagId: "100000112", tagValueId: [1] },
            { tagId: "100000317", tagValueId: [1] },
            { tagId: "100000444", tagValueId: [1] },
            { tagId: "100000445", tagValueId: [1] },
            { tagId: "600015000", tagValueId: ["1"] },
            { tagId: "600029050", tagValueId: ["1"] },
            { tagId: "600137885", tagValueId: ["1"] }
        ],
        transportTypes: ["urgent_express"]
    };

    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    })
        .then(response => {
            if (!response.ok) {
                api1_fail_number++;
                console.log("api1_fail_number:"+api1_fail_number);
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();

        })
        .then(data => {
            api1_fail_number = 0;
            var jsonObject  = data;
            var sku_list = jsonObject['data']['productInfo']['attrSizeList']['sale_attr_list'][goods_id]['sku_list'];
            console.log(sku_list);

            var stock_map = {};
            var index = 0;
            var price = jsonObject['data']['productInfo']['getPrice']['salePrice']['amount'];
            sku_list.forEach((item) => {
                if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                    stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
                }else{
                    stock_map[index] = item['stock'];
                }
                index++;

            })

            var type = "sheinstock_s1";
            var id = msg.data.id;
            console.log(id);
            console.log(stock_map);
            console.log(price);
            chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });


        })
        .catch(error => {
            console.error('Error:', error);
            api1_fail_number++;
            console.log("api1_fail_number:"+api1_fail_number);
        });
}


function getHeaderByType(type){
    console.log("getHeaderByType",type);
    if(sm_eror===true){
        let requestHeader ={
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'anti-in': '0_1.9.1_c38d61_-qx5b0yIhYmNyQg4_nzJw02_XsG7Wbct9SKxL8BesDsAtw5l6XjE4uY2weB9dAatfxMSTdlKbd01lOIVfhNNpdD137c835Lx4N4DCfMSfp66DcYAsPXeyIXkj6hz0reu9PPJ-i9Ry-ZcN2QH_fSWLo5hd5uQECpV0q-zBPYRkrx2LUddIH1SEyjz9DNwu173w-XOcJ0sVk_ubuqPT4t3HK7g-8SiJodsQcItiljQVsOCayA9OoYE14OarnEA2HZXsIqKvxi7aidKvdwY7KteHbcLfxjF2_GwfxFfTY9csb6o0b6HX9MvXvcP05Ho2pepxfZ3XTeqw4PYkyHkKqVDxqBwg1xSJKlEOKyXD3SkCaGcVNrmEfP8_6VioIYou7MCZ0TcH6iVDiN5q2AbhJ1XshURP7yOqnZLmjdf8G2l_XfOQ3SHgIIQlG9JFYKoNkZ2MjKdquUeEpPjJ5pR_aH1QrYgeHv9z3AWK2jbjQ4bsfbO0uM_4ZK_iI_qGhaC_QRrOa9RCu_aG2ilaoiDocXnrKv5jUamfWt-IySkyjAikHFo0rybUKZehMiIhoRoTWfeJSE62J0vRjR76_TgrG1XerIZyAG6HNa-Ny1wi_3ZRqsA4RrM5WWmYIrH_MfsI2q1waNo1JJZO9EiXgKFd3kCQJseDQFFf-7CR8uJDYYd7C9i0iGwk8gOyXmswakoO2qKQD_ZaLia0mfiHOd4kXSAfJqNNyqG_vTjeSEXNmZRwN4cGoln1A8FkBEKsMUc6uY7m',
            'armortoken': 'T0_3.3.0_HrzEkoY1JjaE3mp_fOTINtzBb-h-EkHI0vvSoOmZuZcgwjbqAfmTkQm-fjEVe-gXeN9a2jl02nli0HXVAdgRVvXqDIfiPnUWKtA5HvEwH3RAxPc4sBDMcXOJpkm0tW_mqFiuAGw6zghfuIDcFn_Vuyd5REj4JUH6F8gsPL3qzJjakISTWpoJfszsJHKxxwy7_1747379001280',
            'priority': 'u=1, i',
            'referer': 'https://s1.shein.com/',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            // Add other needed headers from the second request here as necessary
        }
        console.log("not have header");
        return requestHeader;
    }
    if(type === 'static_v2' && header_header_static_v2){
        let requestHeader = {};
        header_header_static_v2.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;

    }else if(type === 'realtime' && header_header_realtime){
        let requestHeader = {};
        header_header_realtime.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;

    }else if(type === 'quickview' && header_quickView){
        let requestHeader = {};
        header_quickView.forEach(header => {
            requestHeader[header.name]=header.value;
        });
        console.log("have header");
        return requestHeader;
    }else{
        return null;
    }


}

var useLocalHeader = false;
function getDataByApiStaticV2(msg){
    console.log("start api 3");
    var url = "https://s1.shein.com/bff-api/product/get_goods_detail_static_data_v2?_ver=1.1.8&_lang=en&goods_id="+msg.data.goods_id+"&mall_code=1&isUserSelectedMallCode=0&isHideEstimatePriceInfo=0&specialSceneType=0&bid=my";


    let requestHeader = getHeaderByType("static_v2")

    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            if(data['code']==='836100'){
                sm_eror= true;
                //clickButton();
                api3_fail_number ++;
                last_fail_api_index = 3;
                console.log("api3_fail_number:"+api3_fail_number);
            }else{
                api3_fail_number = 0;
                doWitdhDataJob(data,msg.data.id,msg);
            }

        })
        .catch(error => {
            api3_fail_number ++;
            last_fail_api_index = 3;
            console.log("api3_fail_number:"+api3_fail_number);
            console.log(error)
        });
}

function get_goods_detail_realtime_data(msg){
    console.log("start api 2");
    var url = "https://s1.shein.com/bff-api/product/get_goods_detail_realtime_data?_ver=1.1.8&_lang=en&goods_id=" + msg.data.goods_id + "&mallCode=1&isUserSelectedMallCode=0&isQueryIsPaidMember=1&isQueryCanTrail=0&isHideEstimatePriceInfo=0&specialSceneType=0&countryId=226&bid=my";

    let requestHeader = getHeaderByType("realtime")

    fetch(url, {
        method: 'GET',
        headers: requestHeader,
        credentials: 'include' // 如果需要携带 cookie
    })
        .then(response => {
            if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
            return response.json();
        })
        .then(data => {
            if(data['code']==='836100'){
                api2_fail_number++;
                last_fail_api_index = 2;
                console.log("api2_fail_number:"+api2_fail_number);
                sm_eror= true;
                //clickButton();
            }else{
                api2_fail_number = 0;
                doWitdhDataJob(data,msg.data.id,msg);
            }

        })
        .catch(error => {
            api2_fail_number ++;
            last_fail_api_index = 2;
            console.log("api2_fail_number:"+api2_fail_number);
            console.log(error);
     });
}



function getStockByQuickView(jsonObject,id,msg){

    let this_good_id = msg.data.goods_id;
    if(jsonObject['code']=="200301"){
        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })

    }else if(jsonObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list']){

        var stock_map = {};
        jsonObject['info']['goods']['attrSizeList']['sale_attr_list'][this_good_id]['sku_list'].forEach(item=>{
            item['sku_sale_attr'].forEach(item1=>{
                if(item1['attr_name_en']=='Size'){
                    stock_map[item1['attr_value_name']] = item['stock'];
                }
            });
        });

        var price = jsonObject['info']['goods']['getPrice']['salePrice']['amount'];

        var type = "sheinstock_s1";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        console.log(stock_map);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

        var all_color_list = [];
        jsonObject['info']['goods']['colorData']['colorList'].forEach(item=>{
            let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
            all_color_list.push(new_color_url);
        });

        if(msg.data.have_order===true){
            console.log(all_color_list)
            type = "sheinstock_s1_new_url";
            chrome.runtime.sendMessage({ data: {type,id, all_color_list,price}, close: false });
        }

    }else if(jsonObject['info']['productInfo']['stock']==0){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }


}


function doWitdhDataJob(jsonObject,id,msg){

    if(jsonObject['code']=="200301"){
        var type = "sheindetaildel";
        var data={}
        data.id = id
        console.log(data);
        chrome.runtime.sendMessage({ data: {type,data }, close: false })

    }else if(jsonObject['info']['saleAttr'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute'] && jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list']){
        var sku_list = jsonObject['info']['saleAttr']['multiLevelSaleAttribute']['sku_list'];
        //console.log(sku_list);

        var stock_map = {};
        var index = 0;
        sku_list.forEach((item) => {
            if(item['sku_sale_attr'] && item['sku_sale_attr'].length>0){
                stock_map[item['sku_sale_attr'][0]['attr_value_name']] = item['stock'];
            }else{
                stock_map[index] = item['stock'];
            }
            index++;

        })

        var price = jsonObject['info']['priceInfo']['salePrice']['amount'];

        var type = "sheinstock_s1";
        console.log(id);
        console.log(stock_map);
        console.log(price);
        console.log(stock_map);
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });

        var all_color_list =[];
        if(jsonObject['info']['saleAttr']['mainSaleAttribute'] && jsonObject['info']['saleAttr']['mainSaleAttribute']['info']){
            jsonObject['info']['saleAttr']['mainSaleAttribute']['info'].forEach(item=>{
                let new_color_url = "/"+item['goods_url_name'].replace(/ /g, '-')+"-p-"+item['goods_id']+".html";
                all_color_list.push(new_color_url);
            });
        }


        if(msg.data.have_order===true){
            console.log(all_color_list)
            type = "sheinstock_s1_new_url";
            chrome.runtime.sendMessage({ data: {type,id, all_color_list,price}, close: false });
        }

    }else if(jsonObject['info']['productInfo']['stock']==0){
        var type = "sheinstock_s1";
        console.log('sheinstock send no stock.');
        var stock_map = {};
        stock_map[0] = 0;
        chrome.runtime.sendMessage({ data: {type,id, stock_map,price}, close: false });
    }


}







